/**
 * @file 工单操作-服务项
 * @author yangjiangming <449654337@qq.com>
 * @date 2018-12-10 20:13:16
 */
layui.extend({
    zmn_validate: 'zmn.validate'
}).define(['layer', 'table', 'form', 'NP', 'zmn_validate', '$http','zmnUtils'], function (exports) {
    var $ = layui.$;
    var layer = layui.layer;
    var table = layui.table;
    var form = layui.form;
    var opCommonUtils = layui.list_modify_common;
    var NP = layui.NP;
    var validate = layui.zmn_validate;
    var $http = layui.$http;

    var zmnUtil = window.zmnUtil;
    var zmnUtils = layui.zmnUtils;

    var groupList = json.groupList;
    var selectedItem = json.selectedItem;

    var allServiceItem = groupList.reduce(function (acc, curr) {
        return acc.concat(curr.serviceItemDTOList);
    }, []);

    var serviceItemData = [];
    var selectedItemData = normalizeSelectedItemData(selectedItem.serviceItemList || []);

    var MAX_SELECTED_ITEM = 10;

    var SAVE_SERVICE_ITEM_URL = '/work/modify/save/serviceitem.action';

    var GET_TIERED_TOTAL_PRICE='/work/modify//serviceitem/tieredtotalprice';

    function normalizeServiceItemData (data) {
        return data.map((item) => {
            item.showPrice = item.itemPrice ? NP.divide(item.itemPrice, 100) : 0;

            return item;
        });
    }

    var getters = {
        getServItemType: () => $("input[name=servItemType]").val()
    };

    /**
     * 根据服务项 Id 获取服务项
     * @param id 服务项 id
     * @returns {T}
     */
    function findServiceItemById (id) {
       return allServiceItem.find(function (item) {
          return item.servItemId  === id;
       })
    }

    function normalizeSelectedItemData (data) {
        var serviceItemData = mapServiceItemData('');
        var selectedItemData = normalizeServiceItemData(data);

        return selectedItemData.map((item) => {
            var serviceItem = serviceItemData.find((sItem) => sItem.servItemId === item.servItemId);

            if (!serviceItem) {
                serviceItem = {};
                serviceItem['disabled'] = true;
            } else {
                serviceItem['disabled'] = false;
            }

            return Object.assign({}, serviceItem, item);
        });
    }

    function calculateTotalAmount() {
        var data = getSelectedItem();
        return data.reduce((acc, curr) => {
            // 计算阶梯价
            if (curr.hasDetail === 2) {
                if (curr.totalPrice && curr.tieredTotalPrice == null) {
                    curr.tieredTotalPrice = curr.totalPrice;
                    acc += NP.divide(curr.totalPrice, 100);
                } else {
                    var params = {
                        orderId: $("input[name='orderId']").val(),
                        itemId: Number.parseInt(curr.servItemId),
                        number: Number.parseInt(curr.number),
                        detailList: curr.detailResultDTOList
                    };
                    $.ajax({
                        url: GET_TIERED_TOTAL_PRICE,
                        type: 'post',
                        async: false,
                        contentType: "application/json",
                        dataType: "json",
                        data: JSON.stringify(params),
                        success: function (response) {
                            if (response.status === 200) {
                                var tieredTotalPrice = response.data;
                                curr.tieredTotalPrice = tieredTotalPrice;
                                curr.itemPrice = curr.itemPrice ? curr.itemPrice : curr.origItemPrice;
                                acc += tieredTotalPrice ? NP.divide(tieredTotalPrice, 100) : 0;
                            } else {
                                layer.msg("请求阶梯价失败" + response.message);
                            }
                        },
                        error: function () {
                            layer.msg('网络错误，请重试');
                        }
                    })
                }
            } else {
                acc += NP.times(curr.showPrice, curr.number);
            }
            return acc;
        }, 0);
    }

    function setTotalAmount () {
        $('#total').text(calculateTotalAmount());
    }

    function mapServiceItemData (groupId) {
        var data;
        if (!groupId) {
            data = groupList.reduce(function (acc, curr) {
                // acc = [...acc, ...curr.serviceItemDTOList];

                if (curr && curr.serviceItemDTOList) {
                    curr.serviceItemDTOList.forEach(function (item) {
                        acc.push(item);
                    });
                }

                return acc;
            }, []);
        } else {
            let rowData = groupList.find((group) => group.servItemGroupId === groupId);
            data = rowData ? rowData.serviceItemDTOList : [];
        }

        return normalizeServiceItemData(data);
    }

    function renderServiceItemTable (data) {
        table.render({
            elem: '#demo',
            height: 390,
            skin: 'nob',
            size: 'lg',
            data: data,
            limit: 1000,
            cols: [[ //表头
                { field: 'servItemName', title: '名称', templet: '#itemTpl'},
                { field: 'showPrice', title: '价格', width:80, align: 'center', style: 'color: #ff7c25', templet: function (d) { console.log(d); return d.manualPrice === 1 ? (d.showPrice  || 0) : '面议' } },
                { field: '操作', title: '性别', width:80, toolbar: '#addTpl'}
            ]],
            done: function () {
                $('#demo').siblings().find('.layui-table-body').height(388);
            }
        });
    }

    function renderSelectedItemTable (data) {
        table.render({
            elem: '#demo1',
            height: 609,
            skin: 'nob',
            size: 'lg',
            data: data,
            limit: 1000,
            cols: [[ //表头
                { field: 'servItemName', title: '服务项目', templet: '#itemTpl'},
                // { width: 30, toolbar: '#minusTpl' },
                { field: 'number', title: '数量', width:80, align: 'center', edit: 'text' },
                // { width: 30, toolbar: '#addTpl' },
                { field: 'showPrice', title: '价格', width: 80, align: 'center', style: 'color: #ff7c25' ,templet: function (d) { console.log(d); return d.priceSplitType === 2 ?'阶梯' : (d.showPrice  || 0) } },
                { title: '操作', width: 100, align: 'center', toolbar: '#editToolbar', fixed: 'right' }
            ]],
            done: function () {
                setTotalAmount();
            }
        });
    }

    /**
     * 初始化页面
     */
    function initPage () {
        serviceItemData = mapServiceItemData('');
        renderServiceItemTable(serviceItemData);
        renderSelectedItemTable(selectedItemData);
    }

    function tableCacheGetterFactory (id) {
        return function () {
            return layui.table.cache[id];
        }
    }

    var getselectedItemTableCache = tableCacheGetterFactory('demo1');

    /**
     * 检查是否需要手动输入价格
     * 1 否 2 是
     * @param rowData
     */
    function checkServiceItemPriceType (rowData, callback) {
        if (rowData.manualPrice === 2) {
            openManualPriceDialog(rowData, callback);
        } else {
            callback(rowData);
        }
    }

    function addServiceItem (rowData) {
        rowData['number'] = 1;
        var data = getselectedItemTableCache();
        data.push(rowData);
        return data;
    }

    function updateServiceItem (index, rowData) {
        rowData['number'] = 1;
        var data = getselectedItemTableCache();
        data[index] = rowData;
        return data;
    }

    function createCheckResult (passed = true, msg = '') {
        return {
            passed: passed,
            msg: msg
        };
    }

    function promiseConfirm (message) {
        var dtd = $.Deferred();

        layer.confirm(message, {
            btn: ['确定', '取消']
        }, function (index) {
            dtd.resolve();
            layer.close(index);
        }, function () {
            dtd.reject();
        });

        return dtd.promise();
    }

    function clearSelectedItemTableCache () {
        getselectedItemTableCache().length = 0;
    }

    function getSelectedItem () {
        return getselectedItemTableCache().filter((item) => {
            return Object.prototype.toString.call(item) === '[object Object]';
        });
    }

    function getSelectedItemTableCacheLength () {
        var result = getSelectedItem();
        return result.length;
    }



    /**
     * 检查服务项是否可添加
     * @param {object} rowData 行数据
     * @returns {boolean}
     */
    function checkServiceItemAddible (rowData) {
        var dtd = $.Deferred();
        var selectedData = getselectedItemTableCache();
        var servItemType = getters.getServItemType();

        if (getSelectedItemTableCacheLength() >= MAX_SELECTED_ITEM) {
            dtd.reject('最多可选择个' + MAX_SELECTED_ITEM + '为服务项');
        } else if (selectedData.some((item) => item.servItemId === rowData.servItemId)) {
            dtd.reject('服务项已存在');
        }
        /*
         * 特殊故障1002 与 普通故障1000 互斥
         */
        else if ((servItemType == 2 || servItemType == 3) && rowData.servItemGroupId == 1000 && selectedData.find((item) => item.servItemGroupId === 1002)) {
            var index = selectedData.findIndex((item) => item.servItemGroupId === 1002);
            var selectedItemName = selectedData[index].servItemName;
            var msg = '由于服务项『' + rowData.servItemName + '』与已选的服务项『' + selectedItemName + '』不能同时选择，添加当前服务项将替换该已选服务项，真的要添加吗？';

            promiseConfirm(msg).then(function () {
                dtd.resolve(index);
            }, dtd.reject);
        }
        else if ((servItemType == 2 || servItemType == 3) && rowData.servItemGroupId == 1002 && selectedData.find((item) => item.servItemGroupId === 1000)) {
            var index = selectedData.findIndex((item) => item.servItemGroupId === 1000);
            var selectedItemName = selectedData[index].servItemName;
            var msg = '由于服务项『' + rowData.servItemName + '』与已选的服务项『' + selectedItemName + '』不能同时选择，添加当前服务项将替换该已选服务项，真的要添加吗？';

            promiseConfirm(msg).then(function () {
                dtd.resolve(index);
            }, dtd.reject);
        }
        /**
         * 1. 全局互斥：
         *  * 点击项目为全局互斥且右边有服务项
         *  * 右边有全局互斥项
         * 2. 局部互斥
         *  * 点击项为局部互斥且右边有局部互斥
         * 3. 不互斥
         */
        else if (rowData.mutexMode === 1 && getSelectedItemTableCacheLength() || selectedData.find((item) => item.mutexMode === 1)) {
            var msg = '由于服务项『' + rowData.servItemName + '』与当前已选的服务项不能同时选择，添加当前服务项将清除当前已选服务项，真的要添加吗？';

            promiseConfirm(msg).then(function () {
                clearSelectedItemTableCache();
                dtd.resolve(-1);
            }, dtd.reject);
        } else if (rowData.mutexMode === 2 && selectedData.find((item) => item.mutexMode === 2)) {
            var index = selectedData.findIndex((item) => item.mutexMode === 2);
            var selectedItemName = selectedData[index].servItemName;
            var msg = '由于服务项『' + rowData.servItemName + '』与已选的服务项『' + selectedItemName + '』不能同时选择，添加当前服务项将替换该已选服务项，真的要添加吗？';

            promiseConfirm(msg).then(function () {
                dtd.resolve(index);
            }, dtd.reject);
        } else {
            dtd.resolve(-1);
        }

        return dtd.promise();
    }

    /**
     * 服务项目列表添加按钮点击事件处理函数
     * @param {object} rowData 行数据
     */
    function handleAddServiceItem (rowData) {
        checkServiceItemAddible(rowData).then(function (index) {
            checkServiceItemPriceType(rowData, function (item) {
                if (index !== -1) {
                    renderSelectedItemTable(updateServiceItem(index, item));
                } else {
                    renderSelectedItemTable(addServiceItem(item));
                }
            });

        }, function (msg) {
            if (msg) {
                layer.msg(msg);
            }
        });
    }

    function openManualPriceDialog (rowData, callback) {
        layer.prompt({
            title: '输入服务项价格',
            formType: 0,
            value: rowData.showPrice || 0,
        }, function (value, index, elem) {
            if (validate.isZDouble(value) && value <= 100000) {
                var itemPrice = NP.times(value, 100);
                if (rowData.negotiableMinPrice && itemPrice < rowData.negotiableMinPrice) {
                    layer.msg('价格不得低于最低价:' + zmnUtils.unit.fenToYuan(rowData.negotiableMinPrice) + "元");
                    return;
                }
                if (rowData.negotiableMaxPrice && itemPrice > rowData.negotiableMaxPrice) {
                    layer.msg('价格不得高于最高价:' + zmnUtils.unit.fenToYuan(rowData.negotiableMaxPrice) + "元");
                    return;
                }
                value = +value;
                var soruceData = findServiceItemById(rowData.servItemId);
                var newPrice = NP.times(value, 100);
                var data = Object.assign({}, rowData, {
                    showPrice: value,
                    itemPrice: newPrice,
                    internalSettlementPrice: soruceData.internalSettlementPrice || newPrice,
                    externalSettlementPrice: soruceData.externalSettlementPrice || newPrice
                });
                callback(data);
                setTotalAmount();
                layer.close(index);
            } else {
                layer.msg('价格只能为0-100000的正数，可保留两位小数');
                $(elem).css('  ', '#FF5722');
            }
        });
        if (rowData.negotiableMinPrice || rowData.negotiableMaxPrice) {
            var holderStr;
            if (rowData.negotiableMinPrice && rowData.negotiableMaxPrice) {
                holderStr = zmnUtils.unit.fenToYuan(rowData.negotiableMinPrice) + ' ~ ' + zmnUtils.unit.fenToYuan(rowData.negotiableMaxPrice);
            } else if (rowData.negotiableMinPrice) {
                holderStr = '最低价：' + zmnUtils.unit.fenToYuan(rowData.negotiableMinPrice) + '元';
            } else if (rowData.negotiableMaxPrice) {
                holderStr = '最高价：' + zmnUtils.unit.fenToYuan(rowData.negotiableMaxPrice) + '元';
            }
            $(".layui-layer-content").find("input").attr("placeholder", holderStr);
        }
    }

    function normalizeParams (formData, serviceItemData) {
        var params = JSON.parse(JSON.stringify(formData));
        var productId = params.productId;
        var productName = params.productName;
        var proExtId = params.proExtId;

        var paramsFields = [
            'servItemId',
            'servItemName',
            'servItemGroupId',
            'servItemGroupName',
            'number',
            'itemPrice',
            'internalSettlementPrice',
            'externalSettlementPrice',
            'tieredTotalPrice',
            'servItemCategId',
            'itemDetailList'
        ];

        params['orderServiceItemList'] = serviceItemData.map((item) => {
            var data = {};
            paramsFields.forEach((field) => {
                data[field] = item[field];
            });

            data['productId'] = productId;
            data['productName'] = productName;
            data['proExtId'] = proExtId;

            return data;
        });


        return params;
    }

    function saveServiceItem (data, params, callback) {
        $http.lockSave(SAVE_SERVICE_ITEM_URL,params, data.elem).then(function () {
            layer.msg('操作成功', { icon: 1, time: 1000 }, function () {
                window.successCallback();
            });
        }, (msg) => {
            layer.msg(msg);
        });
    }

    /**
     * 初始化页面事件
     */
    function initEvent () {
        // 监听服务等级按钮点击事件
        $('.group-wrapper').on('click', 'button', function () {
            var $this = $(this);
            var groupId = $this.data('id');

            if ($this.parent().hasClass('active')) {
                return;
            }

            $this.parent().addClass('active').siblings().removeClass('active');

            serviceItemData = mapServiceItemData(groupId);
            renderServiceItemTable(serviceItemData);
        });

        // 监听服务项目列表工具条点击事件
        table.on('tool(serviceItem)', function (rowObj) {
            var rowData = rowObj.data;

            switch (rowObj.event) {
                case 'add':
                    handleAddServiceItem(rowData);
                    break;
                default:
                    break;
            }
        });

        // 监听已选服务项目列表工具条点击事件
        table.on('tool(selectedItem)', function (rowObj) {
            var rowData = rowObj.data;
            switch (rowObj.event) {
                case 'delete':
                    rowObj.del();
                    setTotalAmount();
                    break;
                case 'add':
                    if (rowData.number >= rowData.maxCount) {
                        layer.msg('本项目允许最大数量为：' + rowData.maxCount);
                        return;
                    }

                    rowData.number = NP.plus(rowData.number, 1);
                    rowObj.update(rowData);
                    setTotalAmount();
                    break;
                case 'minus':
                    if (rowData.number === 1) {
                        rowObj.del();
                    } else {
                        rowData.number = NP.minus(rowData.number, 1);
                        rowObj.update(rowData);
                    }
                    setTotalAmount();
                    break;
                case 'edit':
                    if (rowData.manualPrice === 2) {
                        openManualPriceDialog(rowData, rowObj.update);
                    }
                    break;
                default:
                    setTotalAmount();
                    break;
            }
        });

        // 监听已选服务项目列表单元格编辑
        table.on('edit(selectedItem)', function (rowObj) {
            var value = rowObj.value;
            var rowData = rowObj.data;

            if (!value) {
                layer.msg('手动输入的最小值为：' + 1);
                rowData.number = 1;
            } else if (value >= (rowData.maxCount || Infinity)) {
                layer.msg('本项目允许最大数量为：' + rowData.maxCount);
                rowData.number = rowData.maxCount;
            }
            setTimeout(function () {
                rowObj.update(rowData);
                setTotalAmount();
            }, 0)
        });

        // 已选服务项列表数量输入框输入事件
        $('.selected-item-wrapper').on('input', '.layui-table-edit', function () {
            var $this = $(this);
            $this.val($this.val().replace(/[^\d]/ig, ''));
        });

        // $('#save').on('click', function () {
        //     console.log(getselectedItemTableCache());
        //     if (!getSelectedItemTableCacheLength()) {
        //         layer.msg('没有服务项可保存');
        //         return;
        //     }
        // });

        form.on('submit(service-item)', function (data) {
            if (!getSelectedItemTableCacheLength()) {
                layer.msg('没有服务项可保存');
                return false;
            }

            var params = normalizeParams(data.field, getSelectedItem());
            saveServiceItem(data, params, function () {
                parent.window.location.reload();
                parent.layer.close(parent.layer.getFrameIndex(window.name));
            });

            return false;
        });
    }

    // 程序入口
    function init () {

      // 初始化页面
      initPage();

      // 初始化事件
      initEvent();

    }


    // 初始化
    init();

    exports('oms_work_modify_serviceitem_edit');
});
